var bcrypt = require('bcryptjs');
var salt = bcrypt.genSaltSync(10);
var jwt = require('jsonwebtoken');
module.exports = async (resquest,response)=>{
    var url = resquest.url; //path?query#hash
    var path = url.split("?")[0];
    var method = resquest.method;

    if(path === "/api/user/register"  && method === "POST"){
        //1. 获取postmam传递来的数据
        var bodyObj = await new Promise((reslove,reject)=>{
            var body = "";
            resquest.on("data",(data)=>{
                body += data.toString()
            })
            resquest.on("end",()=>{
                var bodyObj = JSON.parse(body);
                reslove(bodyObj)
            })
        })
        var {username,password} = bodyObj;

        //2. 判断用户名是否已经被注册！
        var sql = `select id from users where username='${username}'`;
        var results = await new Promise((reslove,reject)=>{
            global.connection.query(sql, (error, results) => {
                if(error){
                    reject(error)
                }else{
                    reslove(results)
                }
            });
        })
        if(results.length > 0 ){
            //用户名已经被注册！
            return{
                data:"error",
                message:"The user name has been registered"
            }
        }

        //3. 对密码进行加盐加密
        password = bcrypt.hashSync(password, salt);

        //4. 拼sql 执行sql 对数据库进行插入操作
        var sql = `insert into users (username,password) values ('${username}','${password}')`;

        var data = await new Promise((reslove,reject)=>{
            global.connection.query(sql, (error, results) => {
                if(error){
                    reject(error)
                }else{
                    reslove(results)
                }
            });
        })

        return {
            data:data
        };
    }

    if(path === "/api/user/login"  && method === "POST"){
        //1. 获取postman传递来的数据 注意点:登录时用户传来的密码是明文 数据库中是密文的
        var bodyObj = await new Promise((reslove,reject)=>{
            var body = "";
            resquest.on("data",(data)=>{
                body += data.toString()
            })
            resquest.on("end",()=>{
                var bodyObj = JSON.parse(body);
                reslove(bodyObj)
            })
        })
        var {username,password} = bodyObj;

        //2. 判断用户名是否已经被注册！
        var sql = `select password from users where username='${username}'`;
        var results = await new Promise((reslove,reject)=>{
            global.connection.query(sql, (error, results) => {
                if(error){
                    reject(error)
                }else{
                    reslove(results)
                }
            });
        })
        if(results.length === 0 ){
            //用户名没有被注册！
            return{
                data:"error",
                message:"The user name is not been registered"
            }
        }

        //3. 用户名是存在的 我们需要检验密码
        var flag = bcrypt.compareSync(password, results[0].password);
        if(flag === false){
            //密码有误
            return{
                data:"error",
                message:"Incorrect password"
            }
        }
        //登入成功 生成登入令牌
        var token = jwt.sign({ username:username},
           'damulovezdy',{ expiresIn: 60 * 60*24*7 });
        return {
            data:token
        };
    }

}